package com.example.asuper.check;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asuper.check.Db.CheckDAL;
import com.example.asuper.check.Helper.SharePrefenceHelper;
import com.example.asuper.check.Helper.StringHelper;
import com.example.asuper.check.Model.CheckModel;
import com.example.asuper.check.SdcardManage.FileService;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class Syncdate extends Activity implements View.OnClickListener {
    private ImageButton imgbtn_upload;
    private ImageButton imgbtn_dowload;
    private Button btSetSpite;
    private CheckDAL mCheckDAL;
    private boolean operateresult;
    private Spinner spCode;
    private static final String[] spinneritem = {"  |  ", "  ~  ", "  ,  "};
    private ArrayAdapter<String> adapter;
    private String spliteCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_syncdate);
        setTitle("数据同步");
        imgbtn_upload = (ImageButton) findViewById(R.id.imgbtn_upload);
        imgbtn_dowload = (ImageButton) findViewById(R.id.imgbtn_download);
        btSetSpite = (Button) findViewById(R.id.bt_sync_setspite);
        spCode = (Spinner) findViewById(R.id.sp_sync_spitecode);

        imgbtn_upload.setOnClickListener(this);
        imgbtn_dowload.setOnClickListener(this);
        btSetSpite.setOnClickListener(this);
        operateresult = false;
        spliteCode = "";
        //将可选内容与ArrayAdapter连接起来
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinneritem);
        //设置下拉列表的风格
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将adapter 添加到spinner中
        spCode.setAdapter(adapter);

        spCode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedItem = spinneritem[position];
                spliteCode = StringHelper.getSpliteStr(selectedItem);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        String currentsplite = SharePrefenceHelper.ReadSharedPreferences("splite_info", "SPLITE", this);
        spCode.setSelection(StringHelper.getSpliteIndex(currentsplite), true);
    }

    @Override
    public void onClick(View v) {
        FileService fileService = null;
        switch (v.getId()) {
            case R.id.imgbtn_upload:
                fileService = new FileService(this);
                boolean exctResult = false;
                String fileName = "out.txt";
                try {
                    CheckDAL DbService = new CheckDAL(this);
                    String conent = DbService.getOutStr(DbService.getOutList("0"));
                    if (!conent.equals("baf86762-e9ae-11e5-ba68-b083fe9dbac0")) {
                        exctResult = fileService.writeContentToSdcard(fileName, conent);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    exctResult=false;
                }
                Toast.makeText(this,exctResult?"导出成功！":"导出失败！",Toast.LENGTH_SHORT).show();
                break;
            case R.id.imgbtn_download:
                showDialog_Layout(this);
                break;
            case R.id.bt_sync_setspite:
                if (SharePrefenceHelper.WriteSharedPreferences("splite_info", "SPLITE", spliteCode, this)) {
                    Toast.makeText(Syncdate.this, "设置分隔符成功！", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(Syncdate.this, "设置分隔符失败！", Toast.LENGTH_LONG).show();
                }
                break;

        }
    }

    //显示基于Layout的AlertDialog
    private boolean showDialog_Layout(Context context) {
        LayoutInflater inflater = LayoutInflater.from(this);
        final View textEntryView = inflater.inflate(
                R.layout.layout_inputbatch, null);
        final EditText edtInput = (EditText) textEntryView.findViewById(R.id.ed_inputbatch_batch);
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(false);
        // builder.setIcon(R.drawable.icon);
        builder.setTitle("确定导入的批次号");
        builder.setView(textEntryView);
        builder.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        if (edtInput.getText() == null || edtInput.getText().toString().equals("")) {
                            operateresult = false;
                            Toast.makeText(Syncdate.this, "导入失败，请输入批次号！", Toast.LENGTH_LONG).show();
                        } else {
                            boolean boolresult = inputDate();//导入数据
                            if (boolresult) {
                                SharedPreferences user = getSharedPreferences("batch_info", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = user.edit();
                                editor.putString("BATCH", edtInput.getText().toString());
                                editor.commit();
                                operateresult = true;
                            } else {
                                operateresult = false;
                            }
                        }
                    }
                });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        operateresult = false;
                    }
                });
        builder.show();
        return operateresult;
    }

    //导入数据
    private boolean inputDate() {
        FileService fileService = new FileService(this);
        ArrayList<CheckModel> result = null;
        result = fileService.getFile("waitcheck.txt");
        boolean addResult = false;
        if (result.size() > 0) {
            mCheckDAL = new CheckDAL(this);
            if (mCheckDAL.deleteCheckData("", "2")) {
                addResult = mCheckDAL.addCheckData(result);
            } else {
                addResult = false;
            }
        }
        Toast.makeText(this, addResult ? "导入成功！" : "导入失败！", Toast.LENGTH_LONG).show();
        return addResult;
    }

//    //写入登陆信息
//    private boolean WriteSharedPreferences(String strName) {
//        try {
//            SharedPreferences user = getSharedPreferences("splite_info", Context.MODE_PRIVATE);
//            SharedPreferences.Editor editor = user.edit();
//            editor.putString("SPLITE", strName);
//            editor.commit();
//        } catch (Exception e) {
//            Toast.makeText(this, "设置分隔符失败！", Toast.LENGTH_LONG).show();
//            return false;
//        }
//        return true;
//    }
}
